package com.car.loan.project.xr.service;

import com.car.loan.common.exception.loan.LoanParameterException;
import com.car.loan.common.utils.BeanUtils;
import com.car.loan.common.utils.SecurityUtils;
import com.car.loan.common.utils.qiniu.QiniuUtil;
import com.car.loan.framework.web.domain.AjaxResult;
import com.car.loan.project.xr.domain.Loan;
import com.car.loan.project.xr.domain.LoanAlbum;
import com.car.loan.project.xr.domain.LoanCar;
import com.car.loan.project.xr.domain.LoanDetail;
import com.car.loan.project.xr.domain.LoanExt;
import com.car.loan.project.xr.domain.LoanInsurance;
import com.car.loan.project.xr.domain.LoanStatus;
import com.car.loan.project.xr.mapper.LoanAlbumMapper;
import com.car.loan.project.xr.mapper.LoanCarMapper;
import com.car.loan.project.xr.mapper.LoanDetailMapper;
import com.car.loan.project.xr.mapper.LoanExtMapper;
import com.car.loan.project.xr.mapper.LoanInsuranceMapper;
import com.car.loan.project.xr.mapper.LoanMapper;
import com.car.loan.project.xr.mapper.LoanStatusMapper;
import com.car.loan.project.xr.service.impl.LoanServiceImpl;
import com.car.loan.project.xr.util.RedisDataUtil;
import com.car.loan.project.xr.util.bo.business.ContractInfoBo;
import com.car.loan.project.xr.util.bo.business.LoanAlbumBo;
import com.car.loan.project.xr.util.enums.ContractInfoStatus;
import com.car.loan.project.xr.util.vo.LoanContractInfoVo;
import com.car.loan.project.xr.util.vo.LoanDetailVo.CreditInfo;
import com.car.loan.project.xr.util.vo.LoanDetailVo.LoanBaseInfoVo;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author huangding
 * @date 2020/2/18 20:01
 */
@Service
public class LoanContractInfoService {

    @Autowired
    private LoanMapper loanMapper;

    @Autowired
    private LoanCarMapper loanCarMapper;

    @Autowired
    private LoanExtMapper loanExtMapper;

    @Autowired
    private LoanDetailMapper loanDetailMapper;

    @Autowired
    private LoanStatusMapper loanStatusMapper;

    @Autowired
    private RedisDataUtil redisDataUtil;

    @Autowired
    private LoanServiceImpl loanService;

    @Autowired
    private LoanInsuranceMapper loanInsuranceMapper;

    @Autowired
    private LoanAlbumMapper loanAlbumMapper;

    @Autowired
    private QiniuUtil qiniuUtil;

    public LoanContractInfoVo getContractInfoDetail(Long loanId) {
        LoanContractInfoVo loanContractInfoVo = new LoanContractInfoVo();
        Optional<Loan> optionalLoan
            = Optional.ofNullable(loanMapper.selectById(loanId));
        Loan loan = optionalLoan.orElseThrow(() -> new LoanParameterException("无该业务数据"));
        //获取数据源
        Optional<LoanCar> optionalLoanCar = loanCarMapper.selectByLoanId(loanId);
        LoanCar loanCar = optionalLoanCar
            .orElseThrow(() -> new LoanParameterException("业务数据车辆信息异常"));
        Optional<LoanExt> optionalLoanExt = loanExtMapper.selectByLoanId(loanId);
        LoanExt loanExt = optionalLoanExt
            .orElseThrow(() -> new LoanParameterException("业务数据扩展信息异常"));

        Optional<LoanDetail> optionalLoanDetail = loanDetailMapper.selectByLoanId(loanId);
        LoanDetail loanDetail = optionalLoanDetail
            .orElseThrow(() -> new LoanParameterException("业务数据详情信息异常"));
        Optional<LoanStatus> optionalLoanStatus = loanStatusMapper.selectByLoanId(loanId);
        LoanStatus loanStatus = optionalLoanStatus
            .orElseThrow(() -> new LoanParameterException("业务数据状态信息异常"));
        //客户信息
        loanContractInfoVo
            .setCustomerInfo(loanService.getCustomerAddBo(loan.getId(), loan.getCustomerId()));
        //基本信息
        LoanBaseInfoVo loanBaseInfoVo = loanService.getLoanBaseInfoVo(loan);
        loanBaseInfoVo.setFileNo(loanDetail.getFileNo());
        loanContractInfoVo.setLoanBaseInfo(loanBaseInfoVo);

        //备注信息
        loanContractInfoVo.setAuditRemark(loanDetail.getAuditRemark());
        loanContractInfoVo.setSecondAuditRemark(loanDetail.getSecondAuditRemark());
        loanContractInfoVo.setBusinessSuggest(loanDetail.getBusinessSuggest());

        //业务信息
        LoanContractInfoVo.BusinessInfo businessInfo = new LoanContractInfoVo.BusinessInfo();
        BeanUtils.copyBeanProp(businessInfo, loanDetail);
        businessInfo.setBankName(redisDataUtil.getBankName(loan.getBankId()));
        businessInfo.setInstallmentAmount(loanExt.getInstallmentAmount());
        businessInfo.setBankRate(loanExt.getBankRate());
        businessInfo.setFinancingAmount(loanExt.getFinancingAmount());
        businessInfo.setTerm(loanExt.getTerm());
        businessInfo.setCarSeries(loanExt.getCarName());
        businessInfo.setCarType(loanCar.getCarType());
        businessInfo.setCarNature(loanCar.getCarNature());
        businessInfo.setSellAmount(loanExt.getSellAmount());
        businessInfo.setInstallmentAmount(loanExt.getInstallmentAmount());
        businessInfo.setFinancingAmount(loanExt.getFinancingAmount());
        businessInfo.setTerm(loanExt.getTerm());
        loanContractInfoVo.setBusinessInfo(businessInfo);

        //录入信息
        ContractInfoBo contractInfoBo = new ContractInfoBo();
        BeanUtils.copyBeanProp(contractInfoBo, loanExt);
        contractInfoBo.setLoanId(loanId.toString());
        contractInfoBo.setOperatorStatus(loanStatus.getContractInfoStatus());
        loanContractInfoVo.setContractInfo(contractInfoBo);

        //车辆信息
        LoanContractInfoVo.CarInfo carInfo = new LoanContractInfoVo.CarInfo();
        BeanUtils.copyBeanProp(carInfo, loanCar);
        loanContractInfoVo.setCarInfo(carInfo);

        //保险信息
        Optional<LoanInsurance> loanInsuranceOptional = loanInsuranceMapper.selectByLoanId(loanId);
        if (loanInsuranceOptional.isPresent()) {
            LoanInsurance loanInsurance = loanInsuranceOptional.get();
            List<LoanInsurance> insuranceCarInfos = loanContractInfoVo.getInsuranceCarInfos();
            insuranceCarInfos.add(loanInsurance);
            loanContractInfoVo.setInsuranceCarInfos(insuranceCarInfos);
        }
        //获取附件
        List<LoanAlbum> loanAlbums = loanAlbumMapper.selectListByLoanId(loanId);
        Map<Integer, List<LoanAlbumBo>> loanAlbumMap = loanAlbums.stream().map(l -> {
            LoanAlbumBo loanAlbumBo = new LoanAlbumBo();
            loanAlbumBo.setUrl(qiniuUtil.getAdminAuthUrl(l.getUrl()));
            loanAlbumBo.setLoanId(l.getLoanId());
            loanAlbumBo.setType(l.getType());
            loanAlbumBo.setDbUrl(l.getUrl());
            loanAlbumBo.setThumbnailUrl(qiniuUtil.getUrlByThumbnail(l.getUrl()));
            return loanAlbumBo;
        }).collect(Collectors.groupingBy(LoanAlbumBo::getType));
        loanContractInfoVo.setLoanAlbumMap(loanAlbumMap);
        //获取车辆评诂信息
        loanContractInfoVo
            .setCarEvaluations(loanService.getCarEvaluationInfo(loanCar.getFrameNo()));
        //获取征信信息
        //担保人，配偶，申请人
        List<CreditInfo> creditInfos = loanService
            .getCreditInfos(loanContractInfoVo.getCustomerInfo());
        loanContractInfoVo.setCreditInfos(creditInfos);
        return loanContractInfoVo;
    }

    public AjaxResult audit(ContractInfoBo contractInfoBo) {

        long loanId = Long.parseLong(contractInfoBo.getLoanId());
        Optional<LoanStatus> optionalLoanStatus = loanStatusMapper.selectByLoanId(loanId);
        LoanStatus loanStatus = optionalLoanStatus
            .orElseThrow(() -> new LoanParameterException("该业务状态数据异常，请联系管理员"));
        if (ContractInfoStatus.INIT.status != loanStatus.getContractInfoStatus()) {
            return AjaxResult.error("当前状态不可再次提交");
        }

        loanStatus.setContractInfoStatus(contractInfoBo.getOperatorStatus());
        loanStatus.setContractInfoId(SecurityUtils.getLoginUserId());
        loanStatus.setContractInfoTime(LocalDateTime.now());
        loanStatusMapper.updateById(loanStatus);

        Optional<LoanExt> optionalLoanExt = loanExtMapper.selectByLoanId(loanId);
        LoanExt loanExt = optionalLoanExt
            .orElseThrow(() -> new LoanParameterException("该业务数据异常，请联系管理员"));
        BeanUtils.copyBeanProp(loanExt, contractInfoBo);
        loanExtMapper.updateById(loanExt);
        return AjaxResult.success();
    }
}
